import Ux from 'ux';

const __pageUp = (reference, pagination) => {
    const {$query = {}} = reference.state;
    // 页码改变 | 尺寸该变
    const {
        pager = {}
    } = $query;
    const pagePre = pager.page;
    const sizePre = pager.size;

    const pagePost = pagination.current;
    const sizePost = pagination.pageSize;
    if (pagePre !== pagePost) {
        return true;
    }
    return sizePre !== sizePost;

}

const __sortNorm = (reference, sort) => {
    const {
        $queryView = {},
    } = reference.state;
    const {
        field, order,
    } = sort;
    if (undefined === order) {
        // 不升序也不降序，直接设置默认查询
        return $queryView.sorter;
    } else {
        return [`${field},${"ascend" === order ? "ASC" : "DESC"}`];
    }
}

const __sortUp = (reference, sort = {}) => {
    const {
        $query = {},
    } = reference.state;
    // 页码改变 | 尺寸该变
    const {
        sorter = []
    } = $query;
    // 构造新的 sorter
    const sortPost = __sortNorm(reference, sort);
    if (sorter.length !== sortPost.length) {
        return true;
    }
    return sorter[0] !== sortPost[0];
}

const __qrUp = (reference, filters = {}) => {
    const {
        $condition = {},
        $terms = {}
    } = reference.state;
    // 只比较部分
    const condition = {};
    Object.keys($terms).forEach(field => {
        const value = $condition[field];
        if (!value) {
            condition[field] = null;
        } else {
            condition[field] = value;
        }
    });
    if (Ux.isDiff(condition, filters)) {
        return Ux.clone(filters);
    }
}

export default (reference) => (pagination, filters, sorter) => {
    const upPage = __pageUp(reference, pagination);

    const upSort = __sortUp(reference, sorter);

    const upCondition = __qrUp(reference, filters);
    const upQr = undefined !== upCondition;
    if (upPage || upSort || upQr) {
        /**
         * 查询条件
         */
        const qr = {};
        if (upQr) {
            // 条件改变，使用改变之后的条件
            Object.keys(upCondition ? upCondition : {})
                .filter(field => null !== upCondition[field])
                .filter(field => qr[field] = upCondition[field]);
        } else {
            // 条件未改变，使用改变之前的条件
            const {$condition = {}} = reference.state;
            Object.keys($condition)
                .filter(field => null !== $condition[field])
                .filter(field => qr[field] = $condition[field]);
        }
        /*
         * 「QR」列过滤方法中默认使用 AND 连接符，简单说多个列过滤
         * 之间会产生累加效果，最终影响查询树的生成。
         */
        qr[""] = true;

        const qrDataFn = Ux.irData(reference);
        // #QR-COMMENT
        const [state, queryRef] = qrDataFn({
            isAppend: true,
            $condition: qr,
        });

        if (pagination) {
            const {current, pageSize} = pagination;
            /*
             * 分页信息
             * 1. current 是当前页
             * 2. pageSize 是每页数据
             */
            queryRef.page(current).size(pageSize);
        }


        /**
         * 排序信息
         * 设置排序字段和排序模式
         * 1. field是排序的字段
         * 2. isAsc是排序模式
         */
        const {field, order} = sorter;
        let $query;
        if (order) {
            const isAsc = "ascend" === order;
            queryRef.sort(field, isAsc);
            $query = queryRef.to();
        } else {
            // 还原到默认值
            const {
                $queryView = {}
            } = reference.state;
            const {sorter = []} = $queryView;
            $query = queryRef.to();
            $query.sorter = sorter;
        }
        state.$query = $query;
        // const queryCond = Ux.qrNorm(qr, {terms: $terms});
        // queryRef.and(queryCond);
        // // const query = Ux.qrComplex(qrData, {state: {$condition: qr, $terms}});
        //
        // const state = {};
        // state.$terms = $terms;
        // if (upQr) {
        //     state.$condition = qr;
        // }
        // state.$query = queryRef.to();
        // /*
        //  * 高亮关键字构造
        //  */
        // const $keyword = {};
        // Object.keys($terms).forEach(field => {
        //     const config = $terms[field];
        //     if ("SEARCH" === config.type && qr.hasOwnProperty(field)) {
        //         const keyword = qr[field];
        //         $keyword[field] = keyword[0];   // 此处 keyword 必定是 []
        //     }
        // });
        // state.$keyword = $keyword;
        // 先更改条件不触发结果，保证列过滤中的更新
        Ux.of(reference).in(state).spinning().loading().handle(() => {
            Ux.dglQrFilter(reference);
        });
    } else {
        Ux.dgDebug({
            pager: upPage,
            sorter: upSort,
            criteria: upQr
        }, "onChange中没有触发任何改变！", "#20B2AA");
    }
}